package com.zbkj.admin.controller;

import com.zbkj.admin.util.AesException;
import com.zbkj.admin.util.WXPublicUtils;
import com.zbkj.common.model.order.StoreOrder;
import com.zbkj.service.service.OrderService;
import com.zbkj.service.service.StoreOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("api/admin/notice")
public class WechatActionController {

    @Autowired
    private StoreOrderService storeOrderService;

    @Autowired
    private OrderService orderService;

    /**
     * 接收来自微信的通知
     * https://shopadmin.bvtek.cn/api/admin/notice/receive
     *
     * @return echostr
     */
    @GetMapping(value = "/receive")
    public String receive(HttpServletRequest request , HttpServletResponse response) throws AesException {
        log.info("接受到了来自微信的通知");
        String msgSignature = request.getParameter("signature");
        String msgTimestamp = request.getParameter("timestamp");
        String msgNonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        if (WXPublicUtils.verifyUrl(msgSignature, msgTimestamp, msgNonce)) {
            return echostr;
        }
        return null;
    }

    /**
     * 接收来自微信的通知
     * 小程序发货消息管理接收事件通知（物流发送和确认收货事件）
     *
     * @return echostr
     */
    @PostMapping(value = "/receive")
    public void receivePost(HttpServletRequest request , HttpServletResponse response) throws AesException, IOException {
        log.info("接受到了来自微信的通知");
        String msgSignature = request.getParameter("signature");
        String msgTimestamp = request.getParameter("timestamp");
        String msgNonce = request.getParameter("nonce");
        //判断是否来自微信请求
        if (WXPublicUtils.verifyUrl(msgSignature, msgTimestamp, msgNonce)) {

            StringBuilder buffer = new StringBuilder();
            BufferedReader reader = request.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            String requestBody = buffer.toString();
            Map<String, Object> stringObjectMap = WXPublicUtils.readStringXmlOut(requestBody);
//            for (Map.Entry<String, Object> entry : stringObjectMap.entrySet()) {
//                String key = entry.getKey();
//                Object value = entry.getValue();
//                System.out.println("Key: " + key);
//                System.out.println("Value: " + value);
//            }
            //订单完成发货时 & 订单结算时
            if(stringObjectMap.get("MsgType").equals("event") && stringObjectMap.get("Event").equals("trade_manage_order_settlement")){

                //确认收货时间，秒级时间戳。结算时推送才有该字段
                if(stringObjectMap.get("confirm_receive_time")!=null && stringObjectMap.get("merchant_trade_no") !=null){
                    StoreOrder storeOrderPram = new StoreOrder();
                    storeOrderPram.setOutTradeNo(stringObjectMap.get("merchant_trade_no").toString());
                    StoreOrder existOrder = storeOrderService.getByEntityOne(storeOrderPram);
                    orderService.take(existOrder.getId());
                }
            }
        }
    }
}
